package com.beiji.usercentert.job;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.beiji.usercentert.model.domain.User;
import com.beiji.usercentert.service.UserService;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Component
public class PreCacheJob {

    @Resource
    private UserService userService;
    @Resource
    private RedissonClient redissonClient;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Scheduled(cron = "50 10 10 * * ? ")
    public void recommendUserInfo() {
        RLock lock = redissonClient.getLock("yupao:procachejob:recommend:local");
        try {
            if (lock.tryLock(0, 30000, TimeUnit.MILLISECONDS)) {
                //指定一个重点用户
                Long userId = 1L;
                String redisKey = String.format("yupo:user:recommend:%s", userId);

                //将前20个数据写入缓存
                ValueOperations<String, Object> opsForValue = redisTemplate.opsForValue();
                Page<User> userPage = userService.page(new Page<>(1, 20));
                opsForValue.set(redisKey, userPage, 30000, TimeUnit.MILLISECONDS);
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            if (lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
    }
}
